package dai.core.base

import dai.core.base.camera.Camera
import org.joml.Matrix4f
import org.lwjgl.opengl.GL30C.*

class Renderer {

    private val shaderProgram:ShaderProgram = ShaderProgram()

    val transformation = Transformation()
    val FOV = Math.toRadians(60.0).toFloat()
    val NEAR = 0.01f
    val FAR = 1000f
    var widthf = 0f
    var heightf = 0f

    val tmpMatrix = Matrix4f()

    fun init(window: Window) {

        widthf = window.width.toFloat()
        heightf = window.height.toFloat()

        // init shader
        val vertexSource = Utils.loadShader("/drawrect.vs.shader")
        val fragSource = Utils.loadShader("/drawrect.fs.shader")
        shaderProgram.initShader(vertexSource, fragSource)
        shaderProgram.createUniform("projectMatrix")
        shaderProgram.createUniform("modelViewMatrix")

        glClearColor(0f, 0f, 0f, 1f)
        glEnable(GL_DEPTH_TEST)
    }

    fun render(items:List<GameItem>,camera: Camera){

        shaderProgram.bind()
        val projectMatrix = transformation.projectMatrix(FOV,widthf,heightf,NEAR,FAR)
        shaderProgram.setUniform("projectMatrix",projectMatrix)

        val viewMatrix = transformation.viewMatrix(camera)

        // render items
        for (item in items){
            val worldMatrix = transformation.worldMatrix(
                item.position,
                item.rotation,
                item.scale
            )
            tmpMatrix.set(viewMatrix).mul(worldMatrix)
            shaderProgram.setUniform("modelViewMatrix",tmpMatrix)
            item.mesh.render()
        }
        shaderProgram.unbind()
    }

    fun cleanup(){
        shaderProgram.cleanUp()
    }
}